import Mock from 'mockjs';

// mock.js 订单列表数据
let list = [];
for (let i = 0; i < 5; i++) {
  list.push(
    Mock.mock({
      key: '@integer(0, 100)',
      orderId: '@id',
      createTime: '@date("yyyy-MM-dd hh:mm:ss")',
      'status|1': ['已完成', '待发货', '已发货', '取消'],
      name: '@cname',
    })
  );
}

Mock.mock(/\/order\/list/, 'get', () => {
  return { code: 1, msg: '获取成功', result: list };
});

Mock.mock(/\/order\/add/, 'post', (options) => {
  console.log('options', options);
  const { body } = options;
  list.push(JSON.parse(body));

  return { code: 1, msg: '添加成功', result: list };
});

Mock.mock(/\/order\/edit/, 'post', (options) => {
  const { body } = options;
  const index = list.findIndex((ele) => ele.orderId === body.orderId);
  list.splice(index, 1, JSON.parse(body));

  return { code: 1, msg: '修改成功', result: list };
});

Mock.mock(RegExp(`/order/get.*`), 'get', (options) => {
  const arr = options.url.split('/');
  const id = arr[arr.length - 1];
  const data = list.find((ele) => ele.orderId === id);
  return { code: 1, msg: '获取成功', result: data };
});

Mock.mock(RegExp(`/order/delete.*`), 'delete', (options) => {
  const arr = options.url.split('/');
  const id = arr[arr.length - 1];
  const index = list.findIndex((ele) => ele.orderId === id);
  list.splice(index, 1);
  return { code: 1, msg: '删除成功' };
});

Mock.mock(/\/order\/pay/, 'post', (options) => {
  const { body } = options;
  const { orderId, payment ,status} = JSON.parse(body);
  const index = list.findIndex((ele) => ele.orderId === orderId);
  if (index !== -1) {
    list[index].payment = payment;
    list[index].status = status;
    return { code: 1, msg: '更新成功', result: list };
  } else {
    return { code: 0, msg: '订单不存在' };
  }
});
Mock.mock(/\/order\/cost/, 'get', (options) => {
    console.log('options', options);
    const list = [];
    for(let i=0;i<2;i++){
        list.push(
            Mock.mock({
                orderId: '@integer(1,2)',
                createTime: '@date("yyyy-MM-dd hh:mm:ss")',
                'status|1': ['已完成', '待发货', '已发货', '取消'],
                name: '@cname',
                cost:'@Integer'
            })
        );
    }
    console.log(list);
    const { url } = options;
    const id = url.split('/').pop();
    const orderId = parseInt(id, 10); // 将字符串id转化为整数类型
    console.log(orderId); // 输出整数类型的id
    const order = list.find((ele) => ele.orderId === orderId);
    if (order) {
        return { code: 1, msg: '获取成功', cost: order.cost };
    } else {
        return { code: 0, msg: '订单不存在',id:id };
    }
});

